package com.bupt.jack.action;

import java.util.Iterator;
import java.util.List;

import org.apache.mahout.cf.taste.impl.model.jdbc.MySQLJDBCDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.LogLikelihoodSimilarity;
import org.apache.mahout.cf.taste.model.JDBCDataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class TestRecomend {
	
	private MysqlDataSource dataSource = new MysqlDataSource();
	
	private List<RecommendedItem> personList;
	
	public String execute(){
		dataSource.setServerName("localhost");
		dataSource.setPortNumber(3306);
		dataSource.setUrl("jdbc:mysql://localhost:3306/preferences");
		dataSource.setDatabaseName("preferences");
		dataSource.setUser("root");
		dataSource.setPassword("zhangjian");
		JDBCDataModel dataModel = new MySQLJDBCDataModel(dataSource,"taste_preferences","user_id","item_id","preference","time_stamp");
		
		int userId = 400;
		
		try{
			
			//UserSimilarity similarity = new PearsonCorrelationSimilarity(dataModel);
			
			UserSimilarity similarity = new LogLikelihoodSimilarity(dataModel);
			
			UserNeighborhood neighborhood = new NearestNUserNeighborhood(5, similarity, dataModel);
			
			Recommender recommender = new GenericUserBasedRecommender(dataModel,neighborhood,similarity);
			
			personList = recommender.recommend(userId, 10);
			
			Iterator<RecommendedItem>iter = personList.iterator();
			
			while ( iter.hasNext()) {
				RecommendedItem item = iter.next();
				System.out.println("itemID:" + item.getItemID() + " itemValue" + item.getValue());
			}
			
			return "success";
		}
		catch(Exception e){
			
			e.printStackTrace();
			
			return "error";
		}
		
	}

	public List<RecommendedItem> getPersonList() {
		return personList;
	}

	public void setPersonList(List<RecommendedItem> personList) {
		this.personList = personList;
	}
	
}
